package pers.cz.testNg;

import pers.cz.json.JsonUtil;
import pers.cz.model.TestCase;
import pers.cz.queue.RequestQueue;
import pers.cz.http.HttpUtils;
import pers.cz.service.impl.TestCaseServiceImpl;
import pers.cz.spring.SpringContextUtil;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: PostGirl-panent
 * @description: TestNg
 * @author: Cheng Zhi
 * @create: 2021-03-13 16:42
 **/
public class TestNg3 {

    Logger logger= LoggerFactory.getLogger(TestNg3.class);

    TestCaseServiceImpl testCaseServiceImpl;
    /**
     * 初始化测试用例的入参
     * @return
     */
    @DataProvider(name = "Data")
    public Object[][] init() {

        testCaseServiceImpl = (TestCaseServiceImpl) SpringContextUtil.getBean("testCaseServiceImpl");
        List<Integer> ids = (List<Integer>) RequestQueue.getHeadQueue();
        if (RequestQueue.deleteHeadQueue() && logger.isDebugEnabled()) {
            logger.debug("删除队首成功");
        }
        List<TestCase> listCases = testCaseServiceImpl.queryAllTestCaseIds(ids);
        // List<TestCase> listCases = this.returnTestCaeList();
        Object[][] objects = new Object[listCases.size()][];
        for (int i=0; i<listCases.size(); i++) {
            Object[] o = new Object[5];
            o[0] = listCases.get(i).getRequest();
            o[1] = listCases.get(i).getExpectedResponse();
            o[2] = listCases.get(i).getCaseName();
            o[3] = String.valueOf(listCases.get(i).getId());
            o[4] = listCases.get(i).getIgnoreFields();
            objects[i] = o;
        }
        return objects;
    }

    /**
     * 测试用例
     */
    @Test(dataProvider = "Data")
    public void testCase(String request, String response, String url, String id, String ignoreFields) {
        String isPass = "0";
        url = "http://10.9.238.220:19006/com.cmcc.sh.boss.interfaces.forcrm";
        // 发送请求
        String result = HttpUtils.getResultByPost(request, url);
        // 将出参入库

        JsonElement jsonResponse = new JsonParser().parse(response);
        JsonElement jsonresult = new JsonParser().parse(result);
        Map<String,String> map = new HashMap();
        if (ignoreFields != null && !"".equals(ignoreFields)) {
            String[] fields = ignoreFields.split(",");
            Arrays.asList(fields);
            for (int i=0; i<fields.length; i++) {
                map.put(fields[i], "ignore");
            }
        }

        String newResponse = JsonUtil.replaceJsonNode(jsonResponse, map).toString();
        String newResult = JsonUtil.replaceJsonNode(jsonresult, map).toString();

        try {
            Assert.assertEquals(newResponse,newResult);
        } catch (AssertionError error) {
            isPass = error.getMessage();
            // 此处要重新抛出异常，要不然报告永远是pass
            throw new AssertionError(error);
        } finally {
            updateTestCase(result, id, isPass);
        }

    }

    /**
     * 将真实的请求响应插入数据库
     * @param result
     * @param id
     */
    public void updateTestCase(String result, String id, String isPass) {

        TestCase testCase = new TestCase();
        testCase.setResultResponse(result);
        testCase.setId(Integer.valueOf(id));
        testCase.setResult(isPass);
        // 如果对比结果中包含错误信息，则结果标识记为1.
        if (isPass != "0") {
            testCase.setResultType(1);
        } else {
            testCase.setResultType(0);
        }
        testCaseServiceImpl.updateTestCase(testCase);
    }
}
